/**
 * Tham khao code tai: 
 * 		https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec
 */
(function() {

	hfrApp.constant('AUTH_EVENTS', {
		loginSuccess: 'auth-login-success',
		loginFailed: 'auth-login-failed',
		logoutSuccess: 'auth-logout-success',
		sessionTimeout: 'auth-session-timeout',
		notAuthenticated: 'auth-not-authenticated',
		notAuthorized: 'auth-not-authorized'
	});
	
	hfrApp.constant('USER_ROLES', {
		all: '*',
		admin: 'admin'
	});
	
	hfrApp.factory('AuthService', function ($http, UserInfo) {
		var authService = {};
	  
		authService.create = function (tokenId, username) {
			UserInfo.setUserInfo(tokenId, username);
		};
	 
		authService.remove = function () {
			UserInfo.removeUserInfo();
		};
		
		
		//Kiem tra tinh xac thuc
		authService.isAuthenticated = function () {
			return !!UserInfo.getTokenId();
		};
	 
		return authService;
	});
	
	hfrApp.run(function ($rootScope, $window, AuthService, UserInfo) {
		if (AuthService.isAuthenticated()) {
	        // user is not allowed
			$rootScope.signedIn = true;
			$rootScope.isAuthenticated = true;
			$rootScope.username = UserInfo.getUsername();
		} else {
	        // user is not logged in
			$rootScope.isAuthenticated = false;
		}
	});
	
	//Storage and get data
	hfrApp.factory("UserInfo", function ($window, $rootScope) {
		return {
			setUserInfo: function(tokenId, username) {
				$window.localStorage && $window.localStorage.setItem("tokenId", tokenId);
				$window.localStorage && $window.localStorage.setItem("username", username);
				return this;
			},
			getTokenId: function() {
				return $window.localStorage && $window.localStorage.getItem("tokenId");
			},
			getUsername: function() {
				return $window.localStorage && $window.localStorage.getItem("username");
			},
			removeUserInfo: function () {
				$window.localStorage && $window.localStorage.removeItem("tokenId");
				$window.localStorage && $window.localStorage.removeItem("username");
				return this;
			}
		}
	});
})();